﻿using APICommond;
using BusinessEntity.Warning;
using learun.util;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Nacos.AspNetCore;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using BusinessEntity.U8;
using BusinessEntity;
using BusinessRule;
using ProjectManApi.Extensions;
using Newtonsoft.Json.Converters;

namespace ProjectManApi.Controllers
{
    public class ContractController : MvcControllerBase
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly INacosServerManager _serverManager;
        public ContractController(INacosServerManager serverManager, IHttpClientFactory httpClientFactory) : base(serverManager)
        {
            _serverManager = serverManager;
            _httpClientFactory = httpClientFactory;
        }
        [HttpPost]
        public async Task<IActionResult> SaveOrg(dynamic org)
        {
            try
            {
                JObject jb = JObject.Parse(org);
                await BusinessRule.Warning.Waring.SaveOrg(org);
                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail("失败" + ex.Message);
            }


        }
        [HttpGet]
        //[AllowAnonymous]
        public async Task<IActionResult> GetSend(string org = "", string formCode = "", string crf = "", string zcbm = "", string zcmc = "", string start = "", string end = "", string zt = "", int current = 1, int size = 20)
        {
            try
            {

                _logger.Log(NLog.LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);

                string orgs = await Getorg();
                if (!org.Contains(orgs))
                {
                    org = orgs;
                }


                (IEnumerable<dynamic>, int) SelectTable = await BusinessRule.Warning.Waring.GetSend(org, crf, zcbm, zcmc, start, end, zt, current, size);
              
              
                List<string> list = new List<string>();
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.id;
                    list.Add(id);
                }

                List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(formCode, GetUserAccount(), list, await GetICApiInfo());
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.id;
                    var spstatus = spitems.Where(ii => ii.businessId == id).FirstOrDefault();
                    string status = "unknown";
                    if (item.status == "-1")
                    {
                        status = "draft";

                    }
                    else if (item.status == "0")
                    {
                        status = "uncheck";

                    }
                    else if (item.status == "1")
                    {
                        status = "checking";

                    }
                    else if (item.status == "2")
                    {
                        status = "checked";

                    }
                    else if (item.status == "3")
                    {
                        status = "reject";

                    }
                    else if (item.status == "4")
                    {
                        status = "invalid";

                    }
                    else
                    {
                        status = "unfilled";
                    }
                    item.panguData = GetPanGudData(spstatus, status);
                }

                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                //_logger.Log(LogLevel.Info, Success(pa).ToJson());
                //return Success(pa);

                _logger.Log(LogLevel.Info, Success(pa).ToJson());
                return Success(pa);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        [HttpGet]
        public async Task<IActionResult> GetSendByID(string id)
        {
            DataTable table = await BusinessRule.Warning.Waring.GetSend(id);
            DataTable assets = await BusinessRule.Warning.Waring.GetSendAssets(id);
            Send send = new Send();
            send = DataToEntity.DataTableToEntity<Send>(table);
            if (table.Rows[0]["fileUpload"].ToString() != "")
            {
                JObject j = JObject.Parse(table.Rows[0]["fileUpload"].ToString());
                send.fileUpload = j.ToObject<FileUploadent>();
            }
            List<SendAssets> list = new List<SendAssets>();
            foreach (DataRow row in assets.Rows)
            {
                SendAssets s = new SendAssets();
                string zcbm = Convert.ToString(row["zcbm"]);
                DataTable ass =await BusinessRule.Warning.U8Data.GetZCKP(zcbm);
                s = DataToEntity.DataTableToEntity<SendAssets>(ass);
                if (s != null)
                {
                    s.zdj = Convert.ToDecimal(row["zdj"]);
                    s.mj = Convert.ToDecimal(row["mj"]);
                    s.jgdw = Convert.ToString(row["jgdw"]);
                    s.Assetid = Convert.ToString(row["aid"]);
                    DataTable dt = await BusinessRule.Warning.Waring.GetAssetFile(id, zcbm);
                    List<SFile> listf = new List<SFile>();
                    listf = DataToEntity.DataTableToEntityList<SFile>(dt) as List<SFile>;
                    s.files = listf;
                    list.Add(s);
                }
            }
            send.assets = list;
            return Success(send);
        }

        [HttpGet]
        public async Task<IActionResult> GetSendByOrg(string org)
        {
            try
            {
                DataTable table = await BusinessRule.Warning.Waring.GetSendByOrg(org);
                return Success(table);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }
        [HttpPost]
        public async Task<IActionResult> DeleteSend(string id)
        {
            string ver = await BusinessRule.Warning.Waring.DeleteSend(id);
            if (ver == "")
            {
                return Success("成功");
            }
            else
            {
                return Fail("失败");
            }
        }

        /// <summary>
        /// 根据单位编号和类型生成代码
        /// </summary>
        /// <param name="Dwdm">单位代码</param>
        /// <param name="Lx">类型</param>
        /// <returns>代码</returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetKey()
        { 
            try
            {

                string zcdm = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                _logger.Log(LogLevel.Info, Success(zcdm).ToJson());
                return Success(zcdm);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> SendAssets([FromBody] JObject str)
        {

            #region "处理接收到的参数"

            //if (str["areacode"].ToString().Trim().Length != 15)
            //{
            //    return Fail("出让方请选择最末级！");
            //}
            //保存传入的参数
            FileUploadent filecodes = new FileUploadent();
            if (null != str["fileUpload"])
            {
                filecodes = str["fileUpload"].ToObject<FileUploadent>();
            }
            string id = "";
            string sope = "add";
            if (str.Property("sope") != null)
            {
                sope = str["sope"].ToString();
            }

            if (sope == "add")
            {
                id = str["id"].ToString();
                if (id != "")
                {
                    await BusinessRule.Warning.Waring.UpdateSend(str, "0");
                }
                id = await BusinessRule.Warning.Waring.SaveSend(str);

                //filecodes.version = id;
                JArray ja = JArray.Parse(str["assets"].ToString());
                foreach (JObject jb in ja)
                {
                    DataTable dt = await BusinessRule.Warning.Waring.GetSendAssets(id);
                    string zcid = "";
                    if (dt.Rows.Count > 0)
                    {
                        if (Convert.ToString(dt.Rows[0]["zcbm"]) == jb["assetcode"].ToString())
                        {
                            zcid = Convert.ToString(dt.Rows[0]["Assetid"]);
                        }
                    }
                    await JavaApi.UploadFileJavaAPI(zcid, filecodes, await GetICApiInfo());
                }
            }
            else if (sope == "edit")
            {
                id = str["id"].ToString();
                if (id == "")
                {
                    id = await BusinessRule.Warning.Waring.SaveSend(str);
                }
                else
                {
                    await BusinessRule.Warning.Waring.UpdateSend(str, "0");
                }
               
                //filecodes.version = id;
                JArray ja = JArray.Parse(str["assets"].ToString());
                foreach (JObject jb in ja)
                {
                    DataTable dt = await BusinessRule.Warning.Waring.GetSendAssets(id);
                    string zcid = "";
                    if (dt.Rows.Count > 0)
                    {
                        if (Convert.ToString(dt.Rows[0]["zcbm"]) == jb["assetcode"].ToString())
                        {
                            zcid = Convert.ToString(dt.Rows[0]["Assetid"]);
                        }
                    }
                    await JavaApi.UploadFileJavaAPI(zcid, filecodes, await GetICApiInfo());
                }
            }
            else if (sope == "submit")
            {
                _logger.Log(LogLevel.Info, "开始提交操作");
                id = str["id"].ToString();
                if (id == "")
                {
                    _logger.Log(LogLevel.Info, "新增数据");
                    id = await BusinessRule.Warning.Waring.SaveSend(str);
                    //filecodes.version = id;
                    if (str.Property("id") != null)
                    {
                        str.Remove("id");
                    }
                    str.Add("id", id);
                    //str["id"] = id;
                    JArray ja = JArray.Parse(str["assets"].ToString());
                    foreach (JObject jb in ja)
                    {
                        DataTable dt = await BusinessRule.Warning.Waring.GetSendAssets(id);
                        string zcid = "";
                        if (dt.Rows.Count > 0)
                        {
                            if (Convert.ToString(dt.Rows[0]["zcbm"]) == jb["assetcode"].ToString())
                            {
                                zcid = Convert.ToString(dt.Rows[0]["Assetid"]);
                            }
                        }
                        await JavaApi.UploadFileJavaAPI(zcid, filecodes, await GetICApiInfo());
                    }
                }

                //bsp = false;

                //var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.合同修改记录.ToString(), ht.id);
                _logger.Log(LogLevel.Info, "开始调用审批流");
                JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = id, amount = "", content = "发布资产" + id, deptName = GetUserDeptName() };
                JavaApi.SPLEnt spl = new JavaApi.SPLEnt();
                spl.businessName = "发布资产";
                spl.businessId = id;
                // spl.publicParamKey = "FEE_PROCESS";
                spl.formCode = filecodes.formCode;
                spl.description = _description.ToJson();
                JObject s = JObject.Parse(str.ToString());
                s.Remove("assets");
                spl.additionInfoJson = Newtonsoft.Json.JsonConvert.SerializeObject(s);
                spl.callbackUrl = "http://ic-xmzc/netapi/Contract/UpdateStatus";
                spl.callbackInterface = "/contract-rule/assets-form/${taskId}/" + id + "/audit";
                spl.callbackView= "/contract-rule/assets-form/" + id + "/view";
                //JavaApi.SPLEnt spl = new JavaApi.SPLEnt("资产发布",id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(str), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);
                //bool bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                //if (!bsp)
                string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());
                _logger.Log(LogLevel.Info, "审批流调用结束");
                //ht.spl = strInstanceId;
                if (strInstanceId.StartsWith("err"))
                {
                    await BusinessRule.Warning.Waring.UpdateSend(str, "-1");
                    return Fail("提交失败，启动工作流异常");
                }
                else
                {
                    _logger.Log(LogLevel.Info, "开始更新数据");
                    if (str["id"].ToString() != "")
                    {
                        await BusinessRule.Warning.Waring.UpdateSend(str, "0");
                    }
                    _logger.Log(LogLevel.Info, "数据更新结束");
                    _logger.Log(LogLevel.Info, "开始同步上传文件");
                    JArray ja = JArray.Parse(str["assets"].ToString());
                    foreach (JObject jb in ja)
                    {
                        DataTable dt = await BusinessRule.Warning.Waring.GetSendAssets(id);
                        string zcid = "";
                        if (dt.Rows.Count > 0)
                        {
                            if (Convert.ToString(dt.Rows[0]["zcbm"]) == jb["assetcode"].ToString())
                            {
                                zcid = Convert.ToString(dt.Rows[0]["Assetid"]);
                            }
                        }
                        await JavaApi.UploadFileJavaAPI(zcid, filecodes, await GetICApiInfo());

                    }
                    _logger.Log(LogLevel.Info, "上传文件结束");
                }
            }
            else
            {
                id = str["id"].ToString();
                if (id == "")
                {
                    id = await BusinessRule.Warning.Waring.SaveSend(str);
                    //filecodes.version = id;
                    if (str.Property("id") != null)
                    {
                        str.Remove("id");
                    }
                    str.Add("id", id);
                    //str["id"] = id;
                    JArray ja = JArray.Parse(str["assets"].ToString());
                    foreach (JObject jb in ja)
                    {
                        DataTable dt = await BusinessRule.Warning.Waring.GetSendAssets(id);
                        string zcid = "";
                        if (dt.Rows.Count > 0)
                        {
                            if (Convert.ToString(dt.Rows[0]["zcbm"]) == jb["assetcode"].ToString())
                            {
                                zcid = Convert.ToString(dt.Rows[0]["Assetid"]);
                            }
                        }
                        await JavaApi.UploadFileJavaAPI(zcid, filecodes, await GetICApiInfo());
                    }
                }
                else
                {
                    await BusinessRule.Warning.Waring.UpdateSend(str, "1");
                    JArray ja = JArray.Parse(str["assets"].ToString());
                    foreach (JObject jb in ja)
                    {
                        DataTable dt = await BusinessRule.Warning.Waring.GetSendAssets(id);
                        string zcid = "";
                        if (dt.Rows.Count > 0)
                        {
                            if (Convert.ToString(dt.Rows[0]["zcbm"]) == jb["assetcode"].ToString())
                            {
                                zcid = Convert.ToString(dt.Rows[0]["Assetid"]);
                            }
                        }
                        await JavaApi.UploadFileJavaAPI(zcid, filecodes, await GetICApiInfo());
                    }
                }
                DataTable data = await BusinessRule.Warning.Waring.GetSendAssets(id);
                DataTable send = await BusinessRule.Warning.Waring.GetSend(id);
                DataRow row = send.Rows[0];
                SendAsset asset = new SendAsset();
                asset.appkey = ConfigHelper.GetConfig().key;
                asset.acctnumb = row["areacode"].ToString();
                asset.acctname = row["areaname"].ToString();
                asset.bankname = row["bankname"].ToString();
                asset.bankno = row["bankno"].ToString();
                asset.contractperson = row["contractperson"].ToString();
                asset.dutyperson = row["dutyperson"].ToString();
                asset.mobilephone = row["mobilephone"].ToString();
                asset.transferorname = row["orgname"].ToString();
                //JArray jax = JArray.Parse(str["assets"].ToString());
                List<Assetd> listd = new List<Assetd>();
                foreach (DataRow sr in data.Rows)
                {
                    string zcbm = sr["zcbm"].ToString();
                    DataTable dataTable = await BusinessRule.Warning.U8Data.GetZCKP(zcbm);
                    Assetd assetd = new Assetd();
                    if (dataTable.Rows.Count > 0)
                    {
                        DataRow dr = dataTable.Rows[0];
                        assetd.assetcode = Convert.ToString(dr["assetcode"]);
                        assetd.assetname = Convert.ToString(dr["assetname"]);
                        assetd.assetclass = Convert.ToString(dr["assetclass"]);
                        assetd.assettype = Convert.ToString(dr["assettype"]);
                        assetd.assetsite = Convert.ToString(dr["assetsite"]);
                        assetd.resourcetype = Convert.ToString(dr["resourcetype"]);
                        assetd.tradeunit = Convert.ToString(dr["tradeunit"]);
                        assetd.orgid = Convert.ToString(dr["orgid"]);

                        assetd.assetid = ConfigHelper.GetConfig().areacode + sr["Assetid"].ToString();
                        assetd.tradearea = sr["mj"].ToString();

                        DataTable dt = await BusinessRule.Warning.Waring.GetAssetFile(id, zcbm);
                        List<BusinessEntity.Warning.Files> listf = new List<BusinessEntity.Warning.Files>();
                        foreach (DataRow r in dt.Rows)
                        {
                            BusinessEntity.Warning.Files f = new BusinessEntity.Warning.Files();
                            f.filename = Convert.ToString(r["filename"]);
                            f.fileurl = Convert.ToString(r["fileurl"]);
                            listf.Add(f);
                        }
                        assetd.attachments = listf;
                        listd.Add(assetd);
                    }
                    else
                    {
                        return Fail("传入的资产在资产卡片中不存在！");
                        // return Json(new ResParameter { code = ResponseCode.fail, message = "传入的资产在资产卡片中不存在" });
                    }
                }
                asset.assets = listd;



                string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                string guiid = Guid.NewGuid().ToString();
                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


                //string body = "{\"projcode\":\"" + procode + "\"}";
                //JObject j = JObject.Parse(body);
                //转为链接需要的格式
                HttpContent httpContent = new JsonContent(asset);
                //client.BaseAddress = new Uri(ConfigHelper.GetConfig().asset);
                client.DefaultRequestHeaders.Add("appkey", ConfigHelper.GetConfig().key);
                client.DefaultRequestHeaders.Add("time", time);
                client.DefaultRequestHeaders.Add("guid", guiid);
                client.DefaultRequestHeaders.Add("sign", APICommond.CreateHeader.ToMD5String(ConfigHelper.GetConfig().key + time + guiid + JsonConvert.SerializeObject(asset) + ConfigHelper.GetConfig().secret));
                string result = "";
                HttpResponseMessage response = client.PostAsync(ConfigHelper.GetConfig().asset + "entryassetinformation", httpContent).Result;
                if (response.IsSuccessStatusCode)
                {
                    Task<string> t = response.Content.ReadAsStringAsync();
                    if (t != null)
                    {
                        result = t.Result;
                        JObject j1 = JObject.Parse(t.Result);
                        if (j1["status"].ToString() == "True")
                        {
                            JObject jb = JObject.Parse(j1["data"].ToString());
                            await BusinessRule.Warning.Waring.InsertContract(jb);
                            string err = await BusinessRule.Warning.Waring.InsertMessage(JsonConvert.SerializeObject(asset), JsonConvert.SerializeObject(t.Result));
                            //return Success("成功");
                        }
                        else
                        {
                            string err = await BusinessRule.Warning.Waring.InsertMessage(JsonConvert.SerializeObject(asset), JsonConvert.SerializeObject(t.Result));
                            return Fail("产交系统返回错误信息");
                           // return Json(new ResParameter { code = ResponseCode.fail, message = "产交系统返回错误信息" });
                        }

                    }
                }
            }
            
            #endregion
            return Success("成功");
        }

        [HttpPost]
        //[AllowAnonymous]
        //[HttpPost]
        public async Task<IActionResult> UpdateStatus(dynamic spjson)
        {
            //module，dealUser，approveStatus，businessName，businessId
            //dynamic spjson
            try
            {
                //_logger.Info(spjson.ToString());
                _logger.Debug(JsonConvert.SerializeObject(spjson));

                //{
                //    "businessId":"1403255058317729793",
                //    "businessName":"quotaDetailServiceImpl",
                //    "opinion":"合格，通过，批钱",
                //    "instanceId":352926,
                //    "taskId":352983
                //}
                //string taskId = spjson.taskId;
                //string businessName = spjson.businessName;
                //string instanceId = spjson.instanceId;

                string moduleid = spjson.module;
                string userid = spjson.dealUser;
                string approveStatus = spjson.approveStatus;//UNCHECK, CHECKING,REJECTED,INVALID,CHECKED

                //operation，值：AGREE（同意），REJECT（驳回），INVALID（作废），ACTIVATION（激活），CANCEL（撤销），RESTART（消审）
                string operation = spjson.operation;
                string businessId = spjson.businessId;
                string businessName = spjson.businessName;

                string additionInfo = spjson.additionInfo;

                //additionInfo： {
                //    sdje
                //    ywid
                //    tname
                //  }


                //这里加了一个审定金额



                if (string.IsNullOrEmpty(businessId))
                {
                    //return Fail("业务id不能为空");
                    return Json(new ResParameter { code = ResponseCode.fail, message = "业务id不能为空" });
                }

                //待提交，未审核，审核中 ，作废 ，已审核 ，驳回 ，撤销
                //DRAFT，UNCHECK, CHECKING,INVALID,CHECKED,RESTART
                string ztz = "0";
                if (approveStatus == "UNCHECK")
                {
                    ztz = "0";
                }
                else if (approveStatus == "DRAFT")//draft
                {
                    ztz = "-1";
                }
                else if (approveStatus == "CHECKING")
                {
                    ztz = "1";
                }
                else if (approveStatus == "INVALID")
                {
                    ztz = "4";
                }
                else if (approveStatus == "CHECKED")
                {
                    ztz = "2";
                    DataTable data = await BusinessRule.Warning.Waring.GetSendAssets(businessId);
                    DataTable send = await BusinessRule.Warning.Waring.GetSend(businessId);
                    DataRow row = send.Rows[0];
                    SendAsset asset = new SendAsset();
                    asset.appkey = ConfigHelper.GetConfig().key;
                    asset.acctnumb = row["bankno"].ToString();
                    asset.acctname = row["areaname"].ToString();
                    asset.bankname = row["bankname"].ToString();
                    asset.bankno = row["yhhh"].ToString(); ;
                    asset.contractperson = row["contractperson"].ToString();
                    asset.dutyperson = row["dutyperson"].ToString();
                    asset.mobilephone = row["mobilephone"].ToString();
                    asset.transferorname = row["orgname"].ToString();
                    string orgid= row["areacode"].ToString();
                    if (orgid.Length > 15)
                    {
                        orgid = orgid.Substring(0,15);
                    }
                    //JArray jax = JArray.Parse(str["assets"].ToString());
                    List<Assetd> listd = new List<Assetd>();
                    foreach (DataRow sr in data.Rows)
                    {
                        string zcbm = sr["zcbm"].ToString();
                        DataTable dataTable = await BusinessRule.Warning.U8Data.GetZCKP(zcbm);
                        Assetd assetd = new Assetd();
                        if (dataTable.Rows.Count > 0)
                        {
                            DataRow dr = dataTable.Rows[0];
                            assetd.assetcode = Convert.ToString(dr["assetcode"]);
                            assetd.assetname = Convert.ToString(dr["assetname"]);
                            assetd.assetclass = Convert.ToString(dr["assetclass"]);
                            assetd.assettype = Convert.ToString(dr["assettype"]);
                            if (Convert.ToString(dr["assetsite"]) == "")
                            {
                                assetd.assetsite = row["areaname"].ToString();
                            }
                            else
                            {
                                assetd.assetsite = Convert.ToString(dr["assetsite"]);
                            }
                            
                            assetd.resourcetype = Convert.ToString(dr["resourcetype"]);
                            assetd.tradeunit = Convert.ToString(dr["tradeunit"]);
                            assetd.orgid =orgid;

                            if (sr["Assetid"].ToString().Length > 17)
                            {
                                assetd.assetid = ConfigHelper.GetConfig().areacode + sr["Assetid"].ToString().Substring(0, 17);
                            }
                            else if (sr["Assetid"].ToString() != "")
                            {
                                assetd.assetid = ConfigHelper.GetConfig().areacode + sr["Assetid"].ToString();
                            }
                            else
                            {
                                assetd.assetid = ConfigHelper.GetConfig().areacode + businessId.Substring(0, 17);
                            }
                            assetd.tradearea = sr["mj"].ToString();

                            DataTable dt = await BusinessRule.Warning.Waring.GetAssetFile(businessId, zcbm);
                            List<BusinessEntity.Warning.Files> listf = new List<BusinessEntity.Warning.Files>();
                            foreach (DataRow r in dt.Rows)
                            {
                                BusinessEntity.Warning.Files f = new BusinessEntity.Warning.Files();
                                f.filename = Convert.ToString(r["filename"]);
                                f.fileurl = Convert.ToString(r["fileurl"]);
                                listf.Add(f);
                            }
                            assetd.attachments = listf;

                            DataTable dt1 = await BusinessRule.Warning.Waring.GetAssetFiles(businessId, zcbm);
                            List<BusinessEntity.Warning.Filesx> listfx = new List<BusinessEntity.Warning.Filesx>();
                            foreach (DataRow r in dt1.Rows)
                            {
                                BusinessEntity.Warning.Filesx f = new BusinessEntity.Warning.Filesx();
                                f.projfilename = Convert.ToString(r["filename"]);
                                f.projfileurl = Convert.ToString(r["fileurl"]);
                                f.projfiletype= Convert.ToString(r["projfiletype"]);
                                listfx.Add(f);
                            }
                            assetd.projattachments = listfx;
                            listd.Add(assetd);
                        }
                        else
                        {
                            //return Fail("传入的资产在资产卡片中不存在！");
                            return Json(new ResParameter { code = ResponseCode.fail, message = "传入的资产在资产卡片中不存在" });
                        }
                    }
                    asset.assets = listd;



                    string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    string guiid = Guid.NewGuid().ToString();
                    var client = _httpClientFactory.CreateClient();
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


                    //string body = "{\"projcode\":\"" + procode + "\"}";
                    //JObject j = JObject.Parse(body);
                    //转为链接需要的格式
                    HttpContent httpContent = new JsonContent(asset);
                    //client.BaseAddress = new Uri(ConfigHelper.GetConfig().asset);
                    client.DefaultRequestHeaders.Add("appkey", ConfigHelper.GetConfig().key);
                    client.DefaultRequestHeaders.Add("time", time);
                    client.DefaultRequestHeaders.Add("guid", guiid);
                    client.DefaultRequestHeaders.Add("sign", APICommond.CreateHeader.ToMD5String(ConfigHelper.GetConfig().key + time + guiid + JsonConvert.SerializeObject(asset) + ConfigHelper.GetConfig().secret));
                    string result = "";
                    HttpResponseMessage response = null;
                    try
                    {
                        _logger.Info("调用产交接口"+ConfigHelper.GetConfig().asset+"数据"+ JsonConvert.SerializeObject(asset));
                        response = client.PostAsync(ConfigHelper.GetConfig().asset + "entryassetinformation", httpContent).Result;
                    }
                    catch (Exception ex1)
                    {
                        _logger.Info("调用产交接口失败发送参数为：" + httpContent.ToJson().ToString());
                        _logger.Info("调用产交接口失败"+ex1.Message+ ResponseCode.fail+ex1.StackTrace);
                        return Json(new ResParameter { code = ResponseCode.fail, message = "无法连接产交系统接口"+ex1.Message });
                    }
                    if (response.IsSuccessStatusCode)
                    {
                        _logger.Info("调用产交接口成功");
                        Task<string> t = response.Content.ReadAsStringAsync();
                        if (t != null)
                        {
                            result = t.Result;
                            _logger.Info("产交系统返回数据："+result);
                            JObject j1 = JObject.Parse(t.Result);
                            if (j1["status"].ToString() == "True")
                            {
                                if (j1["data"].ToString() != "")
                                {
                                    JObject jb = JObject.Parse(j1["data"].ToString());
                                    await BusinessRule.Warning.Waring.InsertContract(jb);
                                }
                                string err = await BusinessRule.Warning.Waring.InsertMessage(JsonConvert.SerializeObject(asset), JsonConvert.SerializeObject(t.Result));
                                //return Success("成功");
                                _logger.Info("更新系统数据状态成功，审核成功");
                            }
                            else
                            {
                                string err = await BusinessRule.Warning.Waring.InsertMessage(JsonConvert.SerializeObject(asset), JsonConvert.SerializeObject(t.Result));
                                //return Fail("产交系统返回错误信息");
                                _logger.Info("更新系统数据状态失败，产交系统未返回正确数据！");
                                return Json(new ResParameter { code = ResponseCode.fail, message = "产交系统返回错误信息:"+j1["message"].ToString() });
                            }

                        }
                    }
                }
                else if (approveStatus == "REJECT")
                {
                    ztz = "3";
                }
                else if (approveStatus == "HANDEL")//202109
                {
                    ztz = "-1";
                }
                else if (approveStatus == "RESTART")//202109
                {
                    ztz = "-1";
                }
                // string ztz = CProTZJHRule.GetXMGLSPZT(approveStatus);



                await BusinessRule.Warning.Waring.UpdateSend(businessId, ztz);


                //if (operation == "RESTART")//消审以后
                //{
                //    ztz = "-1";//未提交的状态
                //}

                //  string strTname = businessName;

                //if (await BaseEditPower.GetEditPowerOpe(businessId, strTname, ztz))
                //{

                //}
                //else
                //{
                //    return Fail("请确认当前数据权限状态");
                //}

                // await BaseEditPower.SetStatus(businessId, strTname, ztz, GetUserName(), userid, CommonHelper.ParseDecimal(sdje));

                #region 加日志
                LogEntity logEntity = new LogEntity();
                logEntity.F_CategoryId = 3;
                logEntity.F_OperateTypeId = ((int)OperationType.Audit).ToString();
                logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Audit);
                logEntity.F_OperateAccount = ContextHelper.GetItem("userName") as string;
                logEntity.F_OperateUserId = ContextHelper.GetItem("userId") as string;
                logEntity.F_Module = Request.Path;
                logEntity.F_IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();
                logEntity.F_ExecuteResult = -1;
                var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
                logEntity.F_ExecuteResultJson = JsonConvert.SerializeObject(spjson, timeConverter);
                //添加日志
                await LogRule.Write(logEntity);
                #endregion


                //return Success("操作成功");
                return Json(new ResParameter { code = ResponseCode.success, message = "成功" });
            }
            catch (Exception ex)
            {
               return Json(new ResParameter { code = ResponseCode.fail, message = "操作失败" + ex.Message });
                //return Fail("操作失败："+ ex.Message);
            }
        }

        [HttpGet]
        public async Task<IActionResult> GetProjresult()
        {
            DataTable table = await BusinessRule.Warning.Waring.GetProjresult();
            return Success(table);
        }

        [HttpGet]
        //[AllowAnonymous]
        public async Task<IActionResult> GetProjects(string crf="",string xmbh="",string xmmc="",string jylx="",string cjzt="",int current = 1, int size = 20)
        {
            _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);


            (DataTable, int) SelectTable = await BusinessRule.Warning.Waring.GetProject(crf,xmbh,xmmc,jylx,cjzt,size, current);
            DataTable table = SelectTable.Item1;
            //table = DateString.Dateformat(table);
            Page pa = new Page();
            pa.records = table;
            pa.total = SelectTable.Item2;

            _logger.Log(LogLevel.Info, Success(pa).ToJson());
            return Success(pa, true);
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetProjectInfo(string projcode)
        {
            _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);


            DataTable pr = await BusinessRule.Warning.Waring.Getpro(projcode);
            DataTable assp = await BusinessRule.Warning.Waring.GetAssetP(projcode);
            ProjectInfo info = new ProjectInfo();
            info.project = DataToEntity.DataTableToEntity<Project>(pr);
            List<AssetP> list = new List<AssetP>();
            list = DataToEntity.DataTableToEntityList<AssetP>(assp) as List<AssetP>;
            info.asset = list;
            DataTable contr = await BusinessRule.Warning.Waring.GetContractInfo(projcode);
            BusinessEntity.Warning.Contract contract = new BusinessEntity.Warning.Contract();
            contract = DataToEntity.DataTableToEntity<BusinessEntity.Warning.Contract>(contr);
            info.contract = contract;
            return Success(info, true);
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> Project([FromBody] JObject str)
        {
            try
            {
                _logger.Debug(JsonConvert.SerializeObject(str));
                await BusinessRule.Warning.Waring.SaveProject1(str);
                string projcode = Convert.ToString(str["projcode"]);
                string functioncode = Convert.ToString(str["functioncode"]);
                string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                string guiid = Guid.NewGuid().ToString();
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    string body = "{\"appkey\":\"" + ConfigHelper.GetConfig().key + "\",\"projcode\":\"" + projcode + "\"}";
                    //string body = "{\"projcode\":\"" + procode + "\"}";
                    JObject j = JObject.Parse(body);
                    //转为链接需要的格式
                    HttpContent httpContent = new JsonContent(j);
                    //client.BaseAddress = new Uri(ConfigHelper.GetConfig().asset);
                    client.DefaultRequestHeaders.Add("appkey", ConfigHelper.GetConfig().key);
                    client.DefaultRequestHeaders.Add("time", time);
                    client.DefaultRequestHeaders.Add("guid", guiid);
                    client.DefaultRequestHeaders.Add("sign", APICommond.CreateHeader.ToMD5String(ConfigHelper.GetConfig().key + time + guiid + JsonConvert.SerializeObject(j) + ConfigHelper.GetConfig().secret));
                    string result = "";
                    switch (functioncode)
                    {
                        case "8"://项目立项
                            HttpResponseMessage response = client.PostAsync(ConfigHelper.GetConfig().asset + "projectpublish", httpContent).Result;
                            if (response.IsSuccessStatusCode)
                            {
                                Task<string> t = response.Content.ReadAsStringAsync();
                                if (t != null)
                                {
                                    result = t.Result;
                                    JObject j1 = JObject.Parse(t.Result);
                                    if (j1["status"].ToString() == "True")
                                    {
                                        string data = j1["data"].ToString();
                                        data = DES.DecryptDES(data, ConfigHelper.GetConfig().desKey);
                                        JObject jb = JObject.Parse(data);
                                        await BusinessRule.Warning.Waring.SaveProject(jb);
                                        string err = await BusinessRule.Warning.Waring.InsertMessage(JsonConvert.SerializeObject(j), JsonConvert.SerializeObject(t.Result));
                                        return SuccessCenter("成功","true");
                                    }
                                    else
                                    {
                                        return SuccessCenter("失败", "false");
                                    }
                                }
                            }
                            break;
                        case "6"://合同录入
                            HttpResponseMessage response1 = client.PostAsync(ConfigHelper.GetConfig().asset + "contractinformation", httpContent).Result;
                            if (response1.IsSuccessStatusCode)
                            {
                                Task<string> t = response1.Content.ReadAsStringAsync();
                                if (t != null)
                                {
                                    result = t.Result;
                                    JObject j1 = JObject.Parse(t.Result);
                                    if (j1["status"].ToString() == "True")
                                    {
                                        string data = j1["data"].ToString();
                                        data = DES.DecryptDES(data, ConfigHelper.GetConfig().desKey);
                                        JObject jb = JObject.Parse(data);
                                        jb["projresult"] = 12;
                                        await BusinessRule.Warning.Waring.SaveProjectendresult(jb);
                                        await BusinessRule.Warning.Waring.InsertContract(jb);
                                        string err = await BusinessRule.Warning.Waring.InsertMessage(JsonConvert.SerializeObject(j), JsonConvert.SerializeObject(t.Result));
                                        return SuccessCenter("成功", "true");
                                    }
                                    else
                                    {
                                        return SuccessCenter("失败", "false");
                                    }
                                }
                            }
                            break;
                        case "9"://项目状态
                            HttpResponseMessage response2 = client.PostAsync(ConfigHelper.GetConfig().asset + "projectendresult", httpContent).Result;
                            if (response2.IsSuccessStatusCode)
                            {
                                Task<string> t = response2.Content.ReadAsStringAsync();
                                if (t != null)
                                {
                                    result = t.Result;
                                    JObject j1 = JObject.Parse(t.Result);
                                    if (j1["status"].ToString() == "True")
                                    {
                                        string data = j1["data"].ToString();
                                        data = DES.DecryptDES(data, ConfigHelper.GetConfig().desKey);
                                        JObject jb = JObject.Parse(data);
                                        await BusinessRule.Warning.Waring.SaveProjectendresult(jb);
                                        string err = await BusinessRule.Warning.Waring.InsertMessage(JsonConvert.SerializeObject(j), JsonConvert.SerializeObject(t.Result));
                                        return SuccessCenter("成功", "true");
                                    }
                                    else
                                    {
                                        return SuccessCenter("失败", "false");
                                    }
                                }
                            }
                            break;
                    }

                    return SuccessCenter("失败", "false");
                }
            }
            catch (Exception ex)
            {
                return SuccessCenter("失败", "false");
            }
        }
        #region "U8"
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetListZCKP(string org = "", string zcbm = "", string zcmc = "", string lbdm = "", int current = 1, int size = 20)
        {
            try
            {

                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);
                if (org == null)
                {
                    org = "";
                }
                string orgs = await Getorg();
               
                if (!org.Contains("99999"))
                {
                    if (!org.Trim().Contains(orgs))
                    {
                        org = orgs;
                    }
                }
                if (org == "")
                {
                    org = "123456x";
                }
                _logger.Log(LogLevel.Info, "权限代码:"+org);

                (DataTable, int) SelectTable = await BusinessRule.Warning.U8Data.GetListZCKP(org, zcbm, zcmc, lbdm, current, size);

                DataTable table = SelectTable.Item1;
                table = DateString.Dateformat(table);
                Page pa = new Page();
                pa.records = table;
                pa.total = SelectTable.Item2;
                return Success(pa);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetLBDM()
        {
            try
            {

                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);



                DataTable SelectTable = await BusinessRule.Warning.U8Data.GetLBDM();

                List<LBDM> lbdms = new List<LBDM>();
                foreach (DataRow row in SelectTable.Rows)
                {
                    if (Convert.ToString(row["lbdm"]).Trim().Length == 2)
                    {
                        LBDM lbdm = new LBDM();
                        lbdm.lbdm = Convert.ToString(row["lbdm"]).Trim();
                        lbdm.lbmc = Convert.ToString(row["lbmc"]).Trim();
                        List<LBDM> list = new List<LBDM>();
                        foreach (DataRow dr in SelectTable.Rows)
                        {
                            if (Convert.ToString(dr["lbdm"]).Trim().Length == 4 && Convert.ToString(dr["lbdm"]).Trim().Substring(0, 2) == lbdm.lbdm)
                            {
                                LBDM lb = new LBDM();
                                lb.lbdm = Convert.ToString(dr["lbdm"]).Trim();
                                lb.lbmc = Convert.ToString(dr["lbmc"]).Trim();
                                list.Add(lb);
                                List<LBDM> listl = new List<LBDM>();
                                foreach (DataRow r in SelectTable.Rows)
                                {
                                    if (Convert.ToString(r["lbdm"]).Trim().Length == 6 && Convert.ToString(r["lbdm"]).Trim().Substring(0, 4) == lb.lbdm)
                                    {
                                        LBDM l = new LBDM();
                                        l.lbdm = Convert.ToString(r["lbdm"]).Trim();
                                        l.lbmc = Convert.ToString(r["lbmc"]).Trim();
                                        listl.Add(l);
                                    }
                                }
                                lb.list = listl;
                            }
                        }
                        lbdm.list = list;
                        lbdms.Add(lbdm);
                    }

                }


                return Success(lbdms, true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }
        #endregion
    }
}
